package com.st.service.impl;

import com.st.dao.*;
import com.st.entity.*;
import com.st.service.IShopOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShopOrderService implements IShopOrderService {
    @Autowired
    private IGoodsDao goodsDao;
    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private IOrderGoodsDao orderGoodsDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private ITradeDao tradeDao;
    @Autowired
    private ICartDao cartDao;
    @Override
    @Transactional//事务注解
    public Order createOrder(Integer userId,String userPhone, OrderGoods og) {
        Map<String,Integer> map=new HashMap<>();
        map.put("id",og.getGoodsId());
        map.put("buyCount",og.getBuyCount());
        //1.扣减库存
        goodsDao.updateCount(map);
        //2.生成订单号  当前时间戳加手机号后4位
       String orderNo=System.currentTimeMillis()+userPhone.substring(userPhone.length()-4);
        //3.创建订单和订单商品详情
        Order order =new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        //计算订单总金额 购买数量*单价
        Goods g=goodsDao.query(new Goods(og.getGoodsId())).get(0);
        BigDecimal price=g.getGoodsPrice();
        BigDecimal money=price.multiply(new BigDecimal(og.getBuyCount()));
        order.setOrderMoney(money);
        order.setOrderStatus(1);//待付款状态
        orderDao.add(order);
        //创建订单商品详情
         og.setOrderNo(orderNo);
         og.setGoodsName(g.getGoodsName());
         og.setGoodsImgUrl(g.getImgUrl());
         og.setGoodsPrice(g.getGoodsPrice());
         og.setTotalMoney(money);
         orderGoodsDao.add(og);
         return order;

    }

    @Override
    @Transactional//事务注解
    public List<Order> createCartOrder(Integer userId, String userPhone, List<Cart> list) {
        List<Order> list1=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Map<String,Integer> map=new HashMap<>();
            map.put("id",list.get(i).getGoodsId());
            map.put("buyCount",list.get(i).getBuyCount());
            //1.扣减库存
            goodsDao.updateCount(map);
            OrderGoods og=new OrderGoods();
            og.setGoodsId(list.get(i).getGoodsId());
            og.setGoodsName(list.get(i).getGoodsName());
            og.setGoodsImgUrl(list.get(i).getImgUrl());
            og.setGoodsPrice(list.get(i).getGoodsPrice());
            og.setBuyCount(list.get(i).getBuyCount());

            //2.生成订单号  当前时间戳加手机号后4位 加上遍历的第几次
            String orderNo=System.currentTimeMillis()+userPhone.substring(userPhone.length()-4)+i;
            //3.创建订单和订单商品详情
            Order order =new Order();
            order.setOrderNo(orderNo);
            order.setUserId(userId);
            //计算订单总金额 购买数量*单价
            BigDecimal price=og.getGoodsPrice();
            System.out.println(price);
            BigDecimal money=price.multiply(new BigDecimal(og.getBuyCount()));
            order.setOrderMoney(money);
            order.setOrderStatus(1);//待付款状态
            orderDao.add(order);
            //创建订单商品详情
            og.setOrderNo(orderNo);
            og.setTotalMoney(money);
            orderGoodsDao.add(og);
          list1.add(order);
        }
    return list1;
    }


    @Override
    @Transactional//事务注解
    public boolean pay(String orderNo, BigDecimal orderMoney, String userPass, Integer userId) {
        //1 判断密码是否正确 //md5加密和加盐处理
        String md5Pass2= String.valueOf(DigestUtils.appendMd5DigestAsHex(userPass.getBytes(StandardCharsets.UTF_8), new StringBuilder("wzf")));
        String md5Pass = DigestUtils.md5DigestAsHex(md5Pass2.getBytes(StandardCharsets.UTF_8));

        List<User> list=userDao.query(new User(userId,md5Pass));
        if (list==null || list.size()==0 ){
            return  false;
        }
        //2判断余额是否足够
        User u=list.get(0);
             //compareTo()返回的结果是int类型 -1 表示小于 0表示等于 1表达大于
        int i= u.getUserMoney().compareTo(orderMoney);
        if (i==-1){
            return false;
        }
        //3扣减余额
        BigDecimal oldMoney=u.getUserMoney();
        u.setUserMoney(oldMoney.subtract(orderMoney));
        userDao.updateMoney(u);
        //4.更新订单状态
        Map<String, String> map = new HashMap<>();
        map.put("orderStatus", "2");
        map.put("ids", orderNo);
        orderDao.updateStatus(map);
        //4.生成交易流水
        Trade trade=new Trade();
        trade.setUserId(userId);
        trade.setOrderNo(orderNo);
        trade.setTradeType(2);
        trade.setTradeMoney(orderMoney);
        tradeDao.add(trade);
        return true;
    }
    /*清空购物车成功后删除购物车*/
    @Override
    @Transactional//事务注解
    public boolean delCart(Cart cart) {
       Integer id= cart.getId();
       Integer a= cartDao.del(id);
        if (a==1){
            return true;
        }else {
            return false;
        }
    }


}
